<template>
  <string-split-format-mul-select
    v-if="mode === 'QUICK' && !isLoading"
    v-model="selects" :filter-function="(val)=>{return val!==''}" :format-function="(val)=>{return val.trim()}"
    :allow-create="allowCreate" :mode="mode" :multiple-limit="multipleLimit" :options="options"
    :placeholder="placeholder"
  />
  <string-split-format-mul-select
    v-else-if="mode === 'NORMAL'"
    v-model="selects" :filter-function="(val)=>{return val!==''}" :format-function="(val)=>{return val.trim()}"
    :allow-create="allowCreate" :mode="mode" :multiple-limit="multipleLimit" :options="options"
    :placeholder="placeholder"
  />
</template>
<script>
import {hiveColumns} from "@/api/lineage/metaHive";
import {concatAndRemoveDuplicate} from "@/utils/array";
import StringSplitFormatMulSelect from "@/views/common/stringSplitFormatMulSelect.vue";

export default {
  name: "HiveColumnsSelect",
  components: {StringSplitFormatMulSelect},
  props: {
    databases: {
      type: Array, default: function () {
        return []
      }
    },
    tables: {
      type: Array, default: function () {
        return []
      }
    },
    value: {
      type: Array, default: function () {
        return []
      }
    },
    addStar: {type: Boolean, default: false},
    allowCreate: {type: Boolean, default: false}, mode: {type: String, default: null},
    placeholder: {type: String, default: '请选择table'},
    multipleLimit: {type: Number, default: 0},
  },

  data() {
    return {
      selects: [],
      options: [],
      isLoading: true
    }
  },

  watch: {
    'value': {
      handler(val) {
        this.selects = val
      }, immediate: true
    },

    'databases': {
      handler() {
        this.list()
        this.selects = []
      }, immediate: false
    },

    'tables': {
      handler() {
        this.list()
        this.selects = []
      }, immediate: false
    },

    'selects': {
      handler(val) {
        this.$emit('input', val)
      }, immediate: false
    }
  },

  created() {
    this.list()
  },

  methods: {
    list() {
      if (this.databases && this.tables) {
        this.options = this.addStar ? ['*'] : [];
        for (let i = 0; i < this.tables.length; i++) {
          if (this.tables[i] === '*') {
            return
          }
        }
        const promises = []
        for (let i = 0; i < this.databases.length; i++) {
          for (let j = 0; j < this.tables.length; j++) {
            const promise = hiveColumns(this.databases[i], this.tables[j])
              .then(res => {
                this.options = concatAndRemoveDuplicate(this.options, res.data)
              }).catch(() => {
                this.$message.error("数据加载失败~~~")
              })
            promises.push(promise)
          }
        }
        Promise.all(promises).then(() => {
          this.isLoading = false
        })
      }
    },
  }
}
</script>

<style scoped>

</style>
